<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <Button type="primary" @click="handleAllocation()">新增</Button>
      <Table
        size="small"
        row-key="id"
        :loading="tableLoading"
        :columns="columns"
        :data="dataList"
        class="ivu-mt-16"
      >
        <template slot-scope="{ row }" slot="status">
          <Button
            v-if="row.status === '1'"
            type="success"
            size="small"
            @click="changeStatus(row)"
            >启用</Button
          >
          <Button
            v-if="row.status === '0'"
            type="error"
            size="small"
            @click="changeStatus(row)"
            >停用</Button
          >
        </template>
        <template slot-scope="{ row }" slot="operation">
          <a @click="handleAllocation(row)">编辑</a>
          <Divider type="vertical" />
          <a @click="delfun(row)" style="color: red;">删除</a>
        </template>
      </Table>
    </Card>
    <Modal
      v-model="modal"
      :title="edit ? '编辑' : '新增'"
      :mask-closable="false"
      draggable
      @on-cancel="handleDrawerCancel()"
    >
      <Form
        :model="formItem"
        :rules="ruleValidate"
        ref="formItem"
        :label-width="80"
      >
        <FormItem label="名称" prop="diseases_name">
          <Input
            v-model="formItem.diseases_name"
            placeholder="请输入"
            clearabl
          />
        </FormItem>
        <FormItem label="排序" prop="sort">
          <Input
            v-model="formItem.sort"
            placeholder="默认在现在排序后+1"
            clearable
          />
        </FormItem>
        <FormItem label="父节点" prop="pid">
          <Select clearable placeholder="默认父节点" v-model="formItem.pid">
            <Option v-for="item in dataList" :key="item.id" :value="item.id">{{
              item.diseases_name
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="状态">
          <i-switch v-model="formItem.status">
            <span slot="open">On</span>
            <span slot="close">Off</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleDrawerCancel()">取消</Button>
        <Button
          type="primary"
          :loading="loading"
          @click="handleSubmit('formItem')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  GetDiseaseList,
  CreateDisease,
  UpdateDisease,
  UpdateDiseasenStatus,
} from "@api/setting";
import { systembasepatientdiseasestruedelete } from "@api/delete";

export default {
  name: "diagnosis",
  data() {
    return {
      modal: false,
      edit: false,
      loading: false,
      tableLoading: false,
      formItem: {
        id: "",
        diseases_name: "",
        sort: "",
        pid: "",
        status: true,
      },
      ruleValidate: {
        diseases_name: [
          { required: true, message: "病种名不可为空", trigger: "blur" },
        ],
      },
      columns: [
        {
          title: "名称",
          key: "diseases_name",
          tree: true,
        },
        {
          title: "状态",
          slot: "status",
        },
        {
          title: "操作",
          slot: "operation",
        },
      ],
      dataList: [],
      pageOpts: [10, 20, 30, 50],
      page: 1,
      pageSize: 10,
      total: 0,
      pid: "0",
    };
  },
  created() {
    this.onLoad();
  },
  methods: {
    delfun(row) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "删除后已绑定的数据将被清空，是否确认删除？",
        onOk: () => {
          systembasepatientdiseasestruedelete({ id: row.id }).then((res) => {
            this.$Message.info("删除成功");
            this.onLoad();
          });
        },
        onCancel: () => {},
      });
    },
    onLoad() {
      /**
       * @description 病情列表
       * @param {Object} param page  {String} 页数
       * @param {Object} param pageSize {String} 条数/页
       */
      this.tableLoading = true;
      const params = this.getParam();
      GetDiseaseList(params)
        .then((res) => {
          this.dataList = res.list;
          this.total = res.total;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    getParam() {
      let params = {
        pid: 0,
      };
      return params;
    },
    changePage(page) {
      this.page = page;
      this.onLoad();
    },
    changePageSize(pagesize) {
      this.pageSize = pagesize;
      this.onLoad();
    },
    handleAllocation(row) {
      this.modal = true;
      this.formItem.status = true;
      if (row) {
        this.edit = true;
        this.formItem = {
          diseases_name: row.diseases_name,
          status: row.status === "1",
          id: row.id,
          sort: row.sort,
          pid: row.pid,
        };
      }
    },
    switchStatus(item = []) {
      let status = false;
      for (let i = 0; i < item.length; i++) {
        if (item[i].status === "1") {
          status = true;
          break;
        } else if (
          item[i].status === "0" &&
          item[i].children &&
          item[i].children.length > 0
        ) {
          this.switchStatus(item[i].children);
        }
      }
      return status;
    },
    changeStatus(row) {
      this.$Modal.confirm({
        title: "切换病种状态",
        content: "确定" + (row.status === "1" ? "停用" : "启用") + "当前病种?",
        onOk: () => {
          const status = this.switchStatus(row.children);
          if (row.children && row.children.length > 0 && status) {
            this.$Message.warning("下面有子病种的父病种不允许禁用");
            return false;
          } else {
            UpdateDiseasenStatus({
              id: row.id,
              status: row.status === "1" ? "0" : "1",
            }).then(() => {
              this.$Message.success("状态切换成功");
              this.onLoad();
            });
          }
        },
      });
    },
    handleDrawerCancel() {
      this.modal = false;
      this.edit = false;
      this.formItem.id = "";
      this.formItem.diseases_name = "";
      this.formItem.sort = "";
      this.formItem.pid = "";
      this.formItem.status = false;
      this.$refs["formItem"].resetFields();
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true;
          const params = JSON.parse(JSON.stringify(this.formItem));
          params.status = this.formItem.status ? "1" : "0";
          if (this.edit) {
            this.updateSubmit(params);
          } else {
            this.createSubmit(params);
          }
        } else {
        }
      });
    },
    createSubmit(params) {
      delete params.id;
      if (params.pid === "") params.pid = 0;
      CreateDisease(params)
        .then(() => {
          this.$Message.success("创建成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    updateSubmit(params) {
      UpdateDisease(params)
        .then(() => {
          this.$Message.success(" 修改成功");
          this.loading = false;
          this.onLoad();
          this.handleDrawerCancel();
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped lang="less">
/deep/ .ivu-table-cell-tree {
  text-align: center;
  .ivu-icon {
    vertical-align: middle;
  }
}
</style>
